<?php

namespace app\api\service\tieba;

use app\api\model\tieba\TiebaLink;
use LinCmsTp5\admin\model\LinUser;
use app\api\model\tieba\TiebaDerivative;
use app\api\model\tieba\TiebaDerivativeVideo;
use app\api\model\tieba\TiebaDerivativeContent;
use app\api\service\token\LoginToken;
use app\lib\exception\tieba\TiebaException;
use think\Db;
use think\Exception;
use think\facade\Cache;

class DerivativeService
{
    private static $instance;
    public static function getInstance(): DerivativeService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function addEvent($params){
        $path = env('runtime_path').'tieba/';
        $uid = LoginToken::getInstance()->getCurrentUid()??"";
        $userCache = Cache::connect(['path'=>$path])->get($uid);
        if (!$userCache){
            Cache::connect(['path'=>$path])->set($uid, time(), 3600);//minutes
        }else{
            $s = $userCache + 5;
            if (time()<$s){
                throw new TiebaException([
                    'msg' => '提交频率过于频繁，请间隔5秒钟',
                    'error_code' => 20006
                ]);
            }else{
                Cache::connect(['path'=>$path])->set($uid, time(), 3600);//minutes
            }
        }
        $event = TiebaDerivative::where("link",$params['link'])->findOrEmpty();
        if (!$event->isEmpty()){
            throw new TiebaException([
                'msg' => '提交链接已存在，请更换链接',
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        if (empty($params['images'])){
            throw new TiebaException([
                'msg' => '图片数组不能为空',
                'error_code' => 20002
            ]);
        }
        # 判断文章是否有重复
        $content = "";
        foreach ($params['data'] as $key=>$val){
            if (!empty($val['content'])){
                $content = mb_substr($val['content'],0,20,'utf-8');
                break;
            }
        }

        $event = TiebaDerivative::where("part_content",$content)->findOrEmpty();
        if (!$event->isEmpty()){
            throw new TiebaException([
                'msg' => '已存在相似的文章！',
                'error_code' => 20002
            ]);
        }


        try {
            $data  = [
                "title"=>$params['title'],
                "source_platform"=>$params['source_platform'],
                "link"=>$params['link'],
                "images"=>$params['images'],
                "content"=>$params['content'],
                "status"=>0,
                "uid"=>$uid,
                "comment"=>$params['comment'],
                "area"=>$params['area']??"",
                "type"=>$params['type'],
                "uuid"=>$params['uuid'],
                "new_title"=>$params['new_title'],
                "pub_time"=>$params['pub_time'],
                "tieba"=>$params['tieba']??"",
                "account"=>$params['account']??"",
                "content_id"=>$params['content_id'],
                "video_id"=>$params['video_id']??null,
                "part_content"=>$content??null,
                "remark"=>$params['remark']??null
            ];
            # 已使用音频解析的文章
            if (!empty($params['video_id'])){
                TiebaDerivativeVideo::where("id",$params['video_id'])
                    ->update(['status'=>5]);
            }

            $list_id = TiebaDerivative::insertGetId($data);
            $k = 0;
            foreach ($params['data'] as $key=>$val){
                $add[] = [
                    "list_id"=>$list_id,
                    "content"=>$val['content']??null,
                    "img"=>$val['img']??null,
                    "create_time"=>date("Y-m-d H:i:s")
                ];
            }
            TiebaDerivativeContent::insertAll($add);

            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new TiebaException([
                'msg' => $e->getMessage(),
                'error_code' => 20003
            ]);
        }
        return true;
    }

    public function upEvent($params){
        $event = TiebaDerivative::where("id",$params['id'])->findOrEmpty();
        if ($event->isEmpty()){
            throw new TiebaException([
                'msg' => "作品不存在",
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            $event->save($params);
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new TiebaException([
                'msg' => $e->getMessage(),
                'error_code' => 20003
            ]);
        }
        return true;
    }

    public function check($params){
        $id = TiebaDerivative::field('id')
            ->where("content_id",$params['content_id'])
            ->where("source_platform",$params['source_platform'])
            ->findOrEmpty();
        if (!$id->isEmpty()){
            throw new TiebaException([
                'msg' => '文章已存在，请勿重复提交',
                'error_code' => 20001
            ]);
        }
        return true;
    }
    public function getList($params){
        $event = TiebaDerivative::field("id,new_title,status,type,uuid,uid,backfill_url,pub_time,comment,tieba,account,remark");
        $pageSize = $params['pageSize'] ?? 50;
        $uid = LoginToken::getInstance()->getCurrentUid()??"";
        $user_key = $params['user_key']??1; # 1写手 2分发
        if ($uid != 1){
            if ($user_key == 1){
                $event->where("uid",$uid);
            }else{
                $event->where("uuid",$uid);
            }
        }
        if (isset($params['status'])){
            if ($params['status'] != ""){
                $event->where('status',$params['status']);
            }
        }
        if (!empty($params['type'])){
            $event->where("type",$params['type']);
        }

        if ($uid == 1 && !empty($params['uname'])){
            $u_id =  LinUser::where('username',$params['uname'])->value('id');
            if (!empty($u_id)){
                $event->where('uuid',$u_id);
            }else{
                $event->where('uuid',0);
            }
        }

        $event->order('id','desc');
        $result = $event->paginate($pageSize)->each(function ($item,$value){
            $item->username = LinUser::where('id',$item->uid)->value('username');
            $item->uname = LinUser::where('id',$item->uuid)->value('username');
        });
        return $result;
    }

    public function getEvent($params){
        $time = date("Y-m-d H:i:s");
        $res = TiebaDerivativeContent::field("id,img,content")->where("list_id",$params['list_id'])
            ->select()->toArray();
        return $res;
    }
    public function excel($params){
        if (empty($params['start_time']) || empty($params['end_time'])){
            return false;
        }

        $data = TiebaDerivative::field('backfill_url,pub_time,account,uid,uuid,area,tieba,type,remark')
            ->whereBetweenTime('pub_time',$params['start_time'],$params['end_time'])
            ->select()->each(function ($item,$value){
                $item->username = LinUser::where('id',$item->uid)->value('username');
                $item->uname = LinUser::where('id',$item->uuid)->value('username');
            })->toArray();
//        $task = new TaskService();
        $xlsName = "订单数据"; // 表名称
        $xlsCell = [
            ['backfill_url', '回填地址'],
            ['pub_time', '发布时间'],
            ['account', '作者'],
            ['username', '写手'],
            ['uname', '分发'],
            ['area', '领域'],
            ['tieba', '落地吧'],
            ['type', '类型'],
            ['remark', '备注'],
        ];// 表头信息
        $result = [
            "xlsName" => $xlsName,
            "xlsCell" => $xlsCell,
            "data" => $data
        ];
        return $result;
    }

    public function backfill($params){
        $event = TiebaDerivative::where("id",$params['id'])->findOrEmpty();
        if ($event->isEmpty()){
            throw new TiebaException([
                'msg' => '文章内容不存在',
                'error_code' => 20001
            ]);
        }

        try {
            $data  = [
                "backfill_url"=>$params['backfill_url'],
                "status"=>3,
            ];
            $event->save($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new TiebaException([
                'msg' => $e->getMessage(),
                'error_code' => 20003
            ]);
        }
        return true;
    }

    public function checklink($params){
        $event = TiebaLink::where("content_id",$params["content_id"])->findOrEmpty();
        $uid = LoginToken::getInstance()->getCurrentUid()??"";
        if (!$event->isEmpty()){
            throw new TiebaException([
                'msg' => '文章已存在，请勿重复提交',
                'error_code' => 20002
            ]);
        }
        DB::startTrans();
        try {
            $data = [
                "link" => $params["link"],
                "content_id" => $params["content_id"],
                "title" => $params["title"],
                "uid" => $uid,
                "source_platform" => $params["source_platform"]
            ];
            TiebaLink::create($data);
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new TiebaException([
                'msg' => $e->getMessage(),
                'error_code' => 20003
            ]);
        }
    }

    public function checkUrl($params){
        $event = TiebaLink::where("content_id",$params["content_id"])->findOrEmpty();
        if (!$event->isEmpty()){
            throw new TiebaException([
                'msg' => '此链接已存在，请勿重复提交',
                'error_code' => 20002
            ]);
        }
        return true;
    }
}
